package com.hrhx.springboot.crawler.plugins.net.ssl;

import cn.edu.hfut.dmic.webcollector.plugin.net.OkHttpRequester;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;

import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author duhongming
 * @version 1.0
 * @description 信任所有证书的请求器
 * 针对爬取的网站是https协议的！
 * @date 2019/11/22 10:22
 */
@Slf4j
public class TrustAllCertificationRequester extends OkHttpRequester {
    public static final TrustAllCerts TRUST_ALL_CERTS = new TrustAllCerts();

    @Override
    public OkHttpClient.Builder createOkHttpClientBuilder() {
        return super.createOkHttpClientBuilder()
                .sslSocketFactory(createSSLSocketFactory(), TRUST_ALL_CERTS)
                .hostnameVerifier(new TrustAllHostnameVerifier());
    }

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
            log.error("SSLSocketFactory create error:{}", e);
        }
        return ssfFactory;
    }
}

/**
 * 校验服务器主机名的合法性
 */
class TrustAllHostnameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
}

/**
 * 证书信任管理器
 */
class TrustAllCerts implements X509TrustManager {
    /**
     * 检查客户端的证书，若不信任该证书则抛出异常
     *
     * @param chain
     * @param authType
     */
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

    /**
     * 检查服务器的证书，若不信任该证书同样抛出异常
     *
     * @param chain
     * @param authType
     * @throws CertificateException
     */
    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

    /**
     * 返回受信任的X509证书数组
     *
     * @return
     */
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}
